<template>
    <div style="height: 100%; width: 100%; display: flex; justify-content: center">
        <div style="height: 75%; width: 1000px; display: flex">
            <div  ref="chatContainer" style="flex: 1; background-image: linear-gradient(to bottom, #f0f8ff 0%, #f0f8ff 65%); width: 100%; height: 100%; overflow-y: auto; position: relative;">
                <div v-for="item in message_arr" style="width: 100%; height: 150px;">
<!--        customer顾客的消息            -->
<!--              {
                    message;'今天有什么好吃的',
                    customerId:111,
                    customerName:'美美'
                  }-->
                    <div v-if="item.customerId" style="position: relative">
                        <img src="/imgs/chat/customer.svg" style="width: 68px; position: absolute; left: 30px">
                        <span style="color: #0a9eed; position: absolute; top: 70px; left: 50px">{{ item.customerName }}</span>
                        <div style="position: absolute; left: 130px; margin-top: 30px; background-color: #8bdaac; border-radius: 6px; padding: 15px">
                            <span style="color: #666666">{{ item.message }}</span>
                            <el-button @click="reply(item.customerId)" style="position: relative;left: 15px;border-radius: 15px" type="danger">回复</el-button>
                        </div>

                    </div>
<!--        自己的消息{userId:'',message:''}            -->
                    <div v-if="item.userId===user.id" style="position: relative">
                        <img src="/imgs/chat/ser.svg" style="width: 68px; position: absolute; right: 30px">
                        <span style="color: #0a9eed; position: absolute; top: 80px; right: 40px">{{ user.username }}</span>
                        <div style="position: absolute; right: 130px; margin-top: 30px; background-color: #ace0f9; border-radius: 6px; padding: 15px">
                            <span style="color: #666666">{{ item.message }}</span>
                        </div>
                    </div>
<!--        机器人的消息            -->
<!--              {
                    message:'顾客已下线~',
                    serId:0,
                    serName:'机器人'
                  }-->
                    <div v-if="item.serId===0" style="position: relative">
                        <img src="/imgs/chat/machine.svg" style="width: 68px; position: absolute; left: 30px">
                        <span style="color: #0a9eed; position: absolute; top: 70px; left: 50px">机器人</span>
                        <div style="position: absolute; left: 130px; margin-top: 30px; background-color: #8bdaac; border-radius: 6px; padding: 15px">
                            <span style="color: #666666">{{ item.message }}</span>
                        </div>
                    </div>
                </div>

                <div v-if="show_message_input" style="height: 150px;width: 1000px;position: fixed;z-index: 10;bottom: 25px">
                    <el-input
                            v-model="message_to_send.message"
                            input-style="height:100px;"
                            maxlength="35"
                            style="width: 100%"
                            show-word-limit
                            placeholder="请输入"
                            type="textarea"
                            resize="none"
                    />
                    <el-button @click="cancel_send_message" type="warning" style="border: none; cursor: pointer; position: absolute; right: 80px; top: 100px">取消</el-button>
                    <el-button @click="send_message" type="success" style="border: none; cursor: pointer; position: absolute; right: 0; top: 100px">发送</el-button>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import {computed, nextTick, onMounted, ref} from 'vue';
import { ElInput, ElButton, ElMessage } from 'element-plus';
import store from "@/store";

let socket = null;
const user = ref(getUser());
const message_to_send = ref({
    userId: user.value.id,
    role: user.value.role,
    username: user.value.username,
    branchId: user.value.branchId,
    message: '',
    toWho: 0
});

const show_message_input = ref(false)

const message_arr = computed(() => store.state.emp_message_arr)//员工管理的消息数组//计算属性

const send_message = () => {
    if (!message_to_send.value.message.trim()) {
        ElMessage.warning('消息为空');
        return;
    }
    if (!socket || socket.readyState !== WebSocket.OPEN) {
        console.error('WebSocket is not open. Ready state:', socket ? socket.readyState : 'Socket is null');
        connect_to_websocket();
    }

    socket.send(JSON.stringify(message_to_send.value));
    //message_arr.value.push({userId:user.value.id,message:message_to_send.value.message});
    store.state.emp_message_arr.push({userId:user.value.id,message:message_to_send.value.message})// sessionStorage: 在当前浏览器窗口关闭后自动删除
    message_to_send.value.message = '';
    scrollToBottom(); // 添加：发送消息后滚动到底部

};

const cancel_send_message = ()=>{
    if(confirm('消息还未发送，确认取消吗？')){
        show_message_input.value = false
        message_to_send.value.message=''
        message_to_send.value.toWho=0
    }
}
const reply = (customerId) =>{
    message_to_send.value.toWho=customerId
    show_message_input.value=true
}

const connect_to_websocket = () => {
    if (socket && socket.readyState === WebSocket.OPEN) {
        console.log('WebSocket is already open.');
        ElMessage.info("WebSocket is already open.");
    } else {
        let userId = user.value.id; // 客服ID
        let role = user.value.role;
        let branchId = user.value.branchId;
        let userRoleBranchId = userId + '_' + role + '_' + branchId;

        socket = new WebSocket(`ws://127.0.0.1:8080/ws/message/${userRoleBranchId}`);//后端服务器地址
        websocket_status();
    }
};

function websocket_status() {
    socket.onopen = () => {
        ElMessage.success('连接打开,现在你可以处理消息了');
    };

    socket.onmessage = (event) => {
        /*发送给客服的消息
            {
            message;'今天上班吗？',
            customerId:111,
            customerName:'bob'
            }
            {
             message:'顾客已下线~',
             serId:0,
             serName:'机器人'
            }
        */
        let message_source = JSON.parse(event.data);
        console.log(message_source)
        //message_arr.value.push(message_source);
        store.state.emp_message_arr.push(message_source)
        scrollToBottom(); // 添加：接收消息后滚动到底部

    };

    socket.onclose = () => {
        ElMessage.warning('连接关闭');
    };

    socket.onerror = (error) => {
        ElMessage.error('WebSocket error:');
    };
}
/*自动滚动到最底部*/
const chatContainer = ref(null); // 添加：引用聊天容器元素

const scrollToBottom = async () => {
    await nextTick(); // 等待DOM更新完成
    chatContainer.value.scrollTop = chatContainer.value.scrollHeight; // 滚动到底部
};


onMounted(() => {
    connect_to_websocket();
    scrollToBottom(); // 添加：发送消息后滚动到底部

});
</script>

<style scoped>
</style>



